﻿using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;
using System.Linq;

namespace Inovout.Gis
{
    [Serializable]
    public class MapTopology
    {
        private List<LayerDescriptor> layers=new List<LayerDescriptor>();
        public List<LayerDescriptor> Layers
        {
            get { return layers; }
        }
        private static MapTopology instance;
        public static MapTopology Get()
        {
            if (instance == null)
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(MapTopology));
                using (FileStream fileStream = new FileStream(typeof(MapTopology).Name + ".layer", FileMode.Open))
                {
                    instance = xmlSerializer.Deserialize(fileStream) as MapTopology;
                }

                groupLayerDescriptors = new List<LayerDescriptor>();
                BuildGroupLayerDescriptors(instance.Layers);
            }
            return instance;
        }
        public void Store()
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(MapTopology));
            using (FileStream fileStream = new FileStream(typeof(MapTopology).Name + ".layer", FileMode.Create))
            {
                xmlSerializer.Serialize(fileStream, this);
            }
        }
        private static List<LayerDescriptor> groupLayerDescriptors;
        public LayerDescriptor Next(string layerName, LayerType layerType)
        {
            LayerDescriptor groupLayerDescriptor = groupLayerDescriptors.Single(groupLayer=>groupLayer.Layers.Exists(layer=>layer.Name.Equals(layerName)));
            return groupLayerDescriptor.Layers.Single(layer=>layer.LayerType==layerType);
        }

        private static  void BuildGroupLayerDescriptors(List<LayerDescriptor> layers)
        {
            foreach (var layer in layers)
            {
                if (layer.LayerType == LayerType.Group)
                {
                    groupLayerDescriptors.Add(layer);
                    BuildGroupLayerDescriptors(layer.Layers);
                }
            }
        }

    }
}
